package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.entity.Activity;
import com.qk.entity.Clue;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: zyx
 * @created: 2025-10-09-10:48
 * @description:
 */
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ClueMapper clueMapper;

    @Override
    public PageResult<Activity> page(Integer channel, Integer type, Integer status, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Activity> rows = activityMapper.selectByPage(channel, type, status);
        PageInfo<Activity> pageInfo = new PageInfo<>(rows);
        return PageResult.<Activity>builder().total((int) pageInfo.getTotal()).rows(pageInfo.getList()).build();
    }

    @Override
    public Activity getById(Integer id) {
        return activityMapper.selectById(id);
    }

    @Override
    public void update(Activity activity) {
        //使用hutool工具包进行参数校验
        boolean hasNullField = BeanUtil.hasNullField(activity, "id", "discount", "voucher","updateTime", "createTime");
        if (hasNullField) {
            throw new RuntimeException("参数错误");
        }
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.update(activity);
    }

    @Override
    public void add(Activity activity) {
        //使用hutool工具包进行参数校验
        boolean hasNullField = BeanUtil.hasNullField(activity, "id", "discount", "voucher","updateTime", "createTime");
        if (hasNullField) {
            throw new RuntimeException("参数错误");
        }
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.add(activity);
    }

    @Override
    public void delete(Integer id) {
        //查询出该活动对应的线索列表，如果有线索，则不能删除
        List<Clue> clues = clueMapper.selectList(Wrappers.<Clue>lambdaQuery().eq(Clue::getActivityId, id));
        if(!clues.isEmpty()){
            CommonException.throwCommonException(ParamEnum.REFERENCE_ERROR);
        }
        activityMapper.delete(id);
    }

    @Override
    public List<Activity> listByChannel(Integer type) {
        return activityMapper.listByChannel(type);
    }
}
